package com.jhd.fuzhou.downloadmanager.manager;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jhd.fuzhou.R;
import com.jhd.fuzhou.downloadmanager.DownLoadService;
import com.jhd.fuzhou.downloadmanager.Utils.DeviceUtils;
import com.jhd.fuzhou.service.GetVersionInfo;
import com.jhd.fuzhou.util.UtilHelper;
import com.jhd.fuzhou.vo.Version;

import net.zigin.commons.util.StringUtil;

import java.io.File;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

import static androidx.core.app.ActivityCompat.startActivityForResult;

/**
 * Created by zs on 2016/7/7.
 */

@RequiresApi(api = Build.VERSION_CODES.O)
public class UpdateManager {

    private Context mContext;
    private ProgressDialog _progressDialog;
    private Intent _intent = null;
    private DownloadReceiver _downloadReceiver;
    private Version v;
    private String apkFile ;
    private static final int INSTALL_PERMISS_CODE = 2;

    public UpdateManager(Context context) {
        this.mContext = context;
        apkFile=mContext.getExternalFilesDir(null).getPath()+ File
                .separator + "M_DEFAULT_DIR/fuzhou.apk";
    }

    /**
     * 检测软件更新
     */
    public void checkUpdate(final boolean isToast) {
        /**
         * 在这里请求后台接口，获取更新的内容和最新的版本号
         */
        Retrofit retrofit= UtilHelper.retrofit(UtilHelper.baseUrls.VERSION);
        GetVersionInfo vs =retrofit.create(GetVersionInfo.class);
        Call<String> jsonForResultCall = vs.getVersionInfo();
        jsonForResultCall.enqueue(new GetVersionInfoCallback());
    }

    private class GetVersionInfoCallback implements Callback<String> {

        @Override
        public void onResponse(Call<String> call, Response<String> response) {

            try {
                String result = response.body();
                if(StringUtil.isNullOrEmpty(result))return;
                JSONObject json = JSONObject.parseObject(result);
                v = JSON.toJavaObject(json, Version.class);
                // 版本的更新信息
                String version_info = v.getInfo();//"更新内容\n" + "    1. 异常处理\n" + "    2. 发布格式统一\n" + "    ";
                int nVersion_code = v.getCode();
                int mVersion_code = DeviceUtils.getVersionCode(mContext);// 当前的版本号

                if (mVersion_code < nVersion_code) {
                    if(v.getForce()){//强制更新
                        execUpdate();
                    }else {
                        // 显示提示对话
                        showNoticeDialog(version_info);
                    }
                } else {
                    //Toast.makeText(mContext, "已经是最新版本", Toast.LENGTH_SHORT).show();
                }


            }catch (Exception e){
                Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_SHORT).show();
            }finally {
//                UtilHelper.scanPower(1, SheetInActivity.this);//恢复扫描功能
            }
        }

        @Override
        public void onFailure(Call<String> call, Throwable t) {
            alertNetError();
//            Toast.makeText(mContext, "网络未连接,稍后再试", Toast.LENGTH_SHORT).show();
        }
    }
    private void execUpdate(){
        if(v!=null){
            if(v.getCode()!=getVersionCode(apkFile,mContext)){
                //动态注册广播接收器
                _downloadReceiver = new DownloadReceiver();
                IntentFilter intentFilter = new IntentFilter();
                intentFilter.addAction(UtilHelper.DOWNLOAD_RECEIVER);
                mContext.registerReceiver(_downloadReceiver, intentFilter);
                initProgressDialog();
                mContext.startService(new Intent(mContext, DownLoadService.class));
            }else{
                checkPhoneVersion();
            }
        }
    }

    private void checkPhoneVersion(){
        if(Build.VERSION.SDK_INT >= 26){
            boolean haveInstallPermission = mContext.getPackageManager().canRequestPackageInstalls();
            if(!haveInstallPermission){
                showUnknownDialog();
            }else{
                installApk(new File(apkFile));
            }
        }else{
            installApk(new File(apkFile));
        }
    }

    private void installApk(File file) {
        Uri uri;
        if (Build.VERSION.SDK_INT >= 24) {
            uri = FileProvider.getUriForFile(mContext.getApplicationContext(), "com.jhd.fuzhou.fileprovider", file);
        } else {
            uri = Uri.fromFile(file);
        }
        Intent install = new Intent(Intent.ACTION_VIEW);
        install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        install.setDataAndType(uri, "application/vnd.android.package-archive");
        // 执行意图进行安装
        mContext.startActivity(install);
    }

    /**
     * 获取apk包的信息：版本号，名称，图标等
     * @param absPath apk包的绝对路径
     * @param context
     */
    private int getVersionCode(String absPath,Context context) {
        int versionCode=0;
        PackageManager pm = context.getPackageManager();
        PackageInfo pkgInfo = pm.getPackageArchiveInfo(absPath, PackageManager.GET_ACTIVITIES);
        if (pkgInfo != null) {
            ApplicationInfo appInfo = pkgInfo.applicationInfo;
            /* 必须加这两句，不然下面icon获取是default icon而不是应用包的icon */
            appInfo.sourceDir = absPath;
            appInfo.publicSourceDir = absPath;
            versionCode=pkgInfo.versionCode;
           /* String appName = pm.getApplicationLabel(appInfo).toString();// 得到应用名
            String packageName = appInfo.packageName; // 得到包名
            String version = pkgInfo.versionName; // 得到版本信息*/
            /* icon1和icon2其实是一样的 */
            /*Drawable icon1 = pm.getApplicationIcon(appInfo);// 得到图标信息
            Drawable icon2 = appInfo.loadIcon(pm);
            String pkgInfoStr = String.format("PackageName:%s, Vesion: %s, AppName: %s", packageName, version, appName);
            Log.i(TAG, String.format("PkgInfo: %s", pkgInfoStr));*/
        }
        return versionCode;
    }

    private void showUnknownDialog() {
        // 构造对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("未知应用");
        builder.setMessage("允许安装未知应用");
        // 更新
        builder.setPositiveButton("允许", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Uri packageURI = Uri.parse("package:"+mContext.getPackageName());
                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,packageURI);
                ((Activity)mContext).startActivityForResult(intent, INSTALL_PERMISS_CODE);
            }
        });
        // 稍后更新
        builder.setNegativeButton("不允许", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        Dialog noticeDialog = builder.create();
        if(!((Activity)mContext).isFinishing())noticeDialog.show();
        Button btnPos = ((AlertDialog) noticeDialog).getButton(DialogInterface.BUTTON_POSITIVE);
        Button btnNeg = ((AlertDialog) noticeDialog).getButton(DialogInterface.BUTTON_NEGATIVE);
        btnPos.setTextColor(mContext.getResources().getColor(R.color.header));
        btnNeg.setTextColor(mContext.getResources().getColor(R.color.header));
    }

    /**
     * 显示更新对话框
     *
     * @param version_info
     */
    private void showNoticeDialog(String version_info) {
        // 构造对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("更新提示");
        builder.setMessage(version_info);
        // 更新
        builder.setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

                execUpdate();
            }
        });
        // 稍后更新
        builder.setNegativeButton("以后更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        Dialog noticeDialog = builder.create();
        if(!((Activity)mContext).isFinishing())noticeDialog.show();
        Button btnPos = ((AlertDialog) noticeDialog).getButton(DialogInterface.BUTTON_POSITIVE);
        Button btnNeg = ((AlertDialog) noticeDialog).getButton(DialogInterface.BUTTON_NEGATIVE);
        btnPos.setTextColor(mContext.getResources().getColor(R.color.header));
        btnNeg.setTextColor(mContext.getResources().getColor(R.color.header));
    }
    public class DownloadReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //拿到进度，更新UI
            if(_progressDialog==null)return;
            int progress = intent.getIntExtra("progress", 0);

            if(progress == 100 || progress<0){
                _progressDialog.dismiss();
                mContext.unregisterReceiver(_downloadReceiver);
                if(progress<0){
                    alertNetError();
//                    Toast.makeText(mContext, "下载失败,请稍后再试", Toast.LENGTH_SHORT).show();
                    return;
                }
            }else {
                _progressDialog.setProgress(progress);
            }
        }

    }

    private void alertNetError(){
        try {
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setTitle("错误");
            builder.setMessage("下载失败,更新没有成功,可能因为网络未连接或不稳定,请在网络正常时再进行更新!");
            builder.setPositiveButton("确定", null);
            Dialog dialog = builder.create();
            if(!((Activity)mContext).isFinishing()) dialog.show();
        }catch (Exception ex){
            System.out.print(ex.getMessage());
            //避免因异常而调用错误机制造成闪退
        }
    }
    private void initProgressDialog(){
        _progressDialog = new ProgressDialog(mContext);
        _progressDialog.setTitle("下载更新");
        _progressDialog.setMessage("正在下载最新版本,请不要关机或退出,稍等片刻...");
        _progressDialog.setCanceledOnTouchOutside(false);//在外边是否取消
        _progressDialog.setCancelable(false);//不许取消
//        progressDialog.setIcon(R.drawable.heart);
        _progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        _progressDialog.setMax(100);

//        progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {//添加按钮
//            @Override
//            public void onClick(DialogInterface dialogInterface, int i) {
//                Toast.makeText(ScrapMenuActivity.this,"取消",Toast.LENGTH_SHORT).show();
//            }
//        });
        if(!((Activity)mContext).isFinishing())_progressDialog.show();

    }

}
